package project.web;

import Utils.db.DruidUtils;
import Utils.db.JdbcUtilsStatic;
import project.pojo.User;
import project.service.UserService;
import project.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@Deprecated()
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Connection conn = DruidUtils.getInstance("jdbc_book.properties").getConnection();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = null;
        try {
            user = userService.login( new User(username, password, null));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (user == null) {
            // 把错误信息返回给网页
            request.setAttribute("msg","用户或密码错误！");
            request.setAttribute("username",username);
            request.getRequestDispatcher("pages/user/login.jsp").forward(request, response);
        } else {
            System.out.println("登录成功！");
            request.getRequestDispatcher("pages/user/login_success.jsp").forward(request, response);
        }
    }

    @Override
    public void destroy() {
        JdbcUtilsStatic.close(conn);
        super.destroy();
    }
}
